<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title>Hello MUI</title>
		<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">
		<meta name="apple-mobile-web-app-capable" content="yes">
		<meta name="apple-mobile-web-app-status-bar-style" content="black">

		<!--标准mui.css-->
		<link rel="stylesheet" href="../../css/mui.min.css">
		<link href="../../css/mui.picker.css" rel="stylesheet" />
		<link href="../../css/mui.poppicker.css" rel="stylesheet" />
		<!--App自定义的css-->
		<!-- <link rel="stylesheet" type="text/css" href="../css/app.css" /> -->
		<style>
			h5 {
				margin: 5px 7px;
			}
			.mui-input-row .mui-btn {
			    line-height: 1.1;
			    float: right;
			    width:65%;
			    padding: 10px 15px;
			}
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav">
			<a class="mui-action-back mui-icon mui-icon-left-nav mui-pull-left"></a>
			<h1 class="mui-title">新增餐品</h1>
			<button type="button" id="butSaveTop" class="mui-btn mui-btn-link  mui-pull-right">
				保存
			</button>
		</header>
		<div class="mui-content">
			<div class="mui-content-padded" style="margin: 5px;">
				
				<form class="mui-input-group" id="fmInput">
					<div class="mui-input-row">
						<label>餐品名:</label>
						<input type="text" placeholder="请输入" v-model="fmMenu.goods_name">
					</div>
					<div class="mui-input-row">
						<label>分类:</label>
						
						<button id='showCatPicker' class="mui-btn mui-btn-block" type='button'>{{catname}}</button>
					</div>

					<div class="mui-input-row">
						<label>价格:</label>
						<input type="number" id="txtPrc" placeholder="请输入" v-model="priceNew">
					</div>
	
					
					<div class="mui-input-row" style="margin: 10px 5px;height:120px">
						<textarea id="textarea" rows="5" placeholder="餐品说明" v-model="fmMenu.goods_desc"></textarea>
					</div>
					
					<div class="mui-input-row" style="margin: 10px 5px;height:180px">
						<table border="0" width="100%">
							<tr>
								<td width="90%" align="center">
									<img :src="fmMenu.picpath" width="150px" height="150px" id="imgMenu" onclick="javascript:showActionSheet(this);return false;"/>
									
								</td>
								<!--
								<td valign="center">
									<table border="0" width="100%">
										<tr>
											<td>
												<button type="button" id="butDel" class="mui-btn mui-btn-primary" >删除</button>
											</td>
										</tr>
										<tr height="10px">
										</tr>
										<tr>
											<td>
												<button type="button" id="butUpload" class="mui-btn mui-btn-primary" onclick="createUpload()">上传</button>
											</td>
										</tr>
									</table>
								</td>
								-->
							</tr>
							
						</table>
					</div>
					
					<div class="mui-button-row">
						<button type="button" id="butCut" class="mui-btn mui-btn-primary" disabled="true">图片选取</button>&nbsp;&nbsp;
						<button type="button" id="butSave" class="mui-btn mui-btn-primary" >确认</button>&nbsp;&nbsp;
						<button type="button" id="butCancel" class="mui-btn mui-btn-danger">取消</button>
					</div>
					
				</form>
				
				<input type="hidden" id="ckjl.id" name="ckjl.id" value="429">  
				
				
			</div>
		</div>
		<script src="../../js/mui.min.js"></script>
		<script src="../../js/vue.min.js"></script>
		<script src="../../js/tools.js"></script>
		<script src="../../js/mui.picker.js"></script>
		<script src="../../js/mui.poppicker.js"></script>
		<script>
			var theVue;
			var m_strImgLocalPath = "";
			var m_bCutPic = false;
			var m_retCutPic;
			
			mui.init({
				swipeBack: true //启用右滑关闭功能
			});
			
			var catPicker = new mui.PopPicker({layer: 2});
			
			var showCatPickerBut = document.getElementById('showCatPicker');
			showCatPickerBut.addEventListener('tap', function(event) 
			{
				sespost('/zdm/AppApi/GoodsFactory/GetGoodsCatsByPCatId',
				{catId:"00001"},
				function(catData)
				{
					catPicker.setData(catData);
				});
				
				catPicker.show(function(items) 
				{
					theVue.fmMenu.bigcatname = items[0].text;
					theVue.fmMenu.littlecatname = items[1].text;
					theVue.fmMenu.t_goods_item_id = items[1].value;
				});
			}, false);
			
			document.getElementById("butCancel").addEventListener('tap', function(e) 
			{
				mui.back();
			});
			
			document.getElementById("butCut").addEventListener('tap', function(e) 
			{
				g_jsonData.putData("retUrl","newmenu.html");
				g_jsonData.putData("localpic",m_strImgLocalPath);
				mui.openWindow({
				    url: "cutepic.html", 
				    id:"cutepic.html"
				  });
			});
			
			document.addEventListener('gotmsg', function(event) 
			{
				if(event.detail.msg == "retPic")
				{
					m_retCutPic = event.detail.retPic; 
					m_bCutPic = true;
					//alert(m_retCutPic.SmallHttpPath);
					document.getElementById("imgMenu").setAttribute("src",m_retCutPic.SmallHttpPath);
				}
			});
			
			function fnSaveData(p_RemotePic)
			{				
            		if(g_jsonData.getData("opMode") == "new")
				{
					theVue.fmMenu.pics.push({"picid":p_RemotePic.FileId,"ismain":1});
					
					sespost('/zdm/AppApi/GoodsFactory/GoodsSave',
					theVue.fmMenu,
					function(stat)
					{
						if(stat.succ == 1)
						{
							mui.toast("保存成功");
							mui.back();
						}
						else
						{
							mui.toast("保存失败");
						}
					});
				}
				else
				{
					theVue.fmMenu.pics[0] = {"picid":p_RemotePic.FileId,"ismain":1};
					
					theVue.fmMenu.goodsId = g_jsonData.getData("editGoodId");
					sespost('/zdm/AppApi/GoodsFactory/GoodsUpdate',
					theVue.fmMenu,
					function(stat)
					{
						if(stat.succ == 1)
						{
							mui.toast("保存成功");
							mui.back();
						}
						else
						{
							mui.toast("保存失败");
						}
					});
				}
			}
			
			function fnSave()
			{
				if(theVue.fmMenu.goods_name.trim() == "")
				{
					mui.toast("商品名称不能为空");
					return;
				}
				
				if(theVue.fmMenu.t_goods_item_id == undefined || theVue.fmMenu.t_goods_item_id.trim() == "")
				{
					mui.toast("请选择商品分类");
					return;
				}
				
				
				if(theVue.fmMenu.goods_desc.trim() == "")
				{
					mui.toast("商品说明不能为空");
					return;
				}
				
				if(m_strImgLocalPath != "")
				{
					if(m_bCutPic)
					{
	                		mui.toast( "截图后上传成功" + m_retCutPic.HttpPath );
						
						fnSaveData(m_retCutPic);
					}
					else
					{
						createUpload(function(retRemotePic)
						{
							
		                		mui.toast( "上传成功" + retRemotePic.HttpPath );
							
							fnSaveData(retRemotePic);
	//						if(g_jsonData.getData("opMode") == "new")
	//						{
	//							sespost('/zdm/AppApi/GoodsFactory/GoodsSave',
	//							theVue.fmMenu,
	//							function(stat)
	//							{
	//								if(stat.succ == 1)
	//								{
	//									mui.toast("保存成功");
	//									mui.back();
	//								}
	//								else
	//								{
	//									mui.toast("保存失败");
	//								}
	//							});
	//						}
	//						else
	//						{
	//							theVue.fmMenu.goodsId = g_jsonData.getData("editGoodId");
	//							sespost('/zdm/AppApi/GoodsFactory/GoodsUpdate',
	//							theVue.fmMenu,
	//							function(stat)
	//							{
	//								if(stat.succ == 1)
	//								{
	//									mui.toast("保存成功");
	//									mui.back();
	//								}
	//								else
	//								{
	//									mui.toast("保存失败");
	//								}
	//							});
	//						}
						});
					}
				}
				else
				{
					if(g_jsonData.getData("opMode") == "edit")
					{
						theVue.fmMenu.goodsId = g_jsonData.getData("editGoodId");
						//alert(theVue.fmMenu.pics.length);
						sespost('/zdm/AppApi/GoodsFactory/GoodsUpdate',
						theVue.fmMenu,
						function(stat)
						{
							if(stat.succ == 1)
							{
								mui.toast("保存成功");
								mui.back();
							}
							else
							{
								mui.toast("保存失败");
							}
						});
					}
					else
					{
						mui.toast("请选择要上传的照片");
					}
				}
			}
			
			document.getElementById("butSave").addEventListener('tap', function(e) 
			{
				fnSave();
			});

			document.getElementById("butSaveTop").addEventListener('tap', function(e) 
			{
				fnSave();
			});


			var nativeWebview, imm, InputMethodManager;
			var initNativeObjects = function() {
				if (mui.os.android) {
					var main = plus.android.runtimeMainActivity();
					var Context = plus.android.importClass("android.content.Context");
					InputMethodManager = plus.android.importClass("android.view.inputmethod.InputMethodManager");
					imm = main.getSystemService(Context.INPUT_METHOD_SERVICE);
				} else {
					nativeWebview = plus.webview.currentWebview().nativeInstanceObject();
				}
			};
			var showSoftInput = function() {
				if (mui.os.android) {
					imm.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
				} else {
					nativeWebview.plusCallMethod({
						"setKeyboardDisplayRequiresUserAction": false
					});
				}
				setTimeout(function() {
					var inputElem = document.querySelector('input');
					inputElem.focus();
					inputElem.parentNode.classList.add('mui-active'); //第一个是search，加上激活样式
				}, 200);
			};
			mui.plusReady(function() {
				initNativeObjects();
				showSoftInput();
			});

		</script>
		
		<script>
		theVue = new Vue({
		    el:'#fmInput',
		    created:function()
		    {
		    		
		    }
		    ,
		    methods:{
		        fnsubmit:function()
		        {
		        
		        }
		    },
		    data:
		    {
		    		priceNew:0,
			    fmMenu:
			    {
					goods_name:"",
					brand:"",
					t_goods_item_id:"",
					express_money:0,
					contact:" ",
					address:" ",
					pack_list:" ",
					goods_desc:"",
					prices:[],
					specs:[],
					pics:[],
					mvfileid:"",
					price_mode:0,
					props:[],
					vals:[],
					store_count:999,
					bigcatname:"",
					littlecatname:"",
					picpath:"../../images/logo1.png"
				}
				
		    },
		    computed: 
		    {
		    		catname:function() 
	        		{	console.log("this.fmMenu.bigcatname="+this.fmMenu.bigcatname);
	        			var strRet = "";
	        			if(this.fmMenu.bigcatname != null && this.fmMenu.bigcatname != "" && this.fmMenu.bigcatname != undefined && this.fmMenu.littlecatname != null && this.fmMenu.littlecatname != "" && this.fmMenu.littlecatname != undefined)
					{
						strRet = this.fmMenu.bigcatname + "," + this.fmMenu.littlecatname;
						console.log("catname=" + strRet);
						if(strRet == ",")
						{
							strRet = "选择分类...";
						}
					}
					else
					{
						strRet = "选择分类...";
					}
		            return strRet;
	        		}
	        	}
		    			
		});
		
		theVue.$watch('priceNew', function (val) 
		{
			if(theVue.fmMenu.prices==undefined)
			{
				return;	
			}
			
			if(theVue.fmMenu.prices.length>0)
			{
				theVue.fmMenu.prices[0].Price = val;
			}
			else
			{
				theVue.fmMenu.prices.push({"prdid":"0","Price":val,"StoreCount":99990,"propVal":[]});
			}
		 	
		});
		</script>
		
		
<script>  
	
	if(g_jsonData.getData("opMode") == "edit")
	{
		sespost('/zdm/AppApi/GoodsFactory/GetGoodsInfo',
		{GoodsId:g_jsonData.getData("editGoodId")},
		function(p_Data)
		{
			theVue.fmMenu = p_Data.goods;
			theVue.priceNew = p_Data.goods.mprice;
			theVue.fmMenu.picpath = p_Data.goods.FilePath.smallimg;
			theVue.fmMenu.pics.push({"picid":p_Data.goods.picid,"ismain":1});
		});
	}
	
	
	
    var procinstid = 0;  
    //初始化页面执行操作  
    function plusReady() {  
        //Android返回键监听事件  
        plus.key.addEventListener('backbutton',function(){  
            //myclose();  
        },false);  
    }  
    if (window.plus) {  
        plusReady();  
    } else {  
        document.addEventListener('plusready', plusReady, false);  
    }  
    
    
    function createUpload(p_callback) 
    {
    		if(m_strImgLocalPath != "")
    		{
    			//alert(m_strImgLocalPath);
//  			if(m_strImgLocalPath.indexOf("file://")>-1)
//  			{
//  				m_strImgLocalPath = m_strImgLocalPath.substring(7,m_strImgLocalPath.length);
//  			}
    			//alert(g_SrvUrl + "/zdm/commonPictures/h5uploadimg.do");
    			var wa = plus.nativeUI.showWaiting();  
	    		var task = plus.uploader.createUpload
	    		(
	    			g_SrvUrl + "/zdm/commonPictures/h5uploadimg.do",
	        		{ method:"POST",blocksize:204800,priority:100,enctype:"multipart/form-data",timeout: 60000},
	        		function ( t, status ) 
	        		{
		            // 上传完成
		            if ( status == 200 ) { 
		                //alert( "Upload success: " + t.url );
		                var result =JSON.parse(t.responseText);
		                //alert("t.responseText="+t.responseText);
		                if(result.length > 0)
		                {
//		                		if(g_jsonData.getData("opMode") == "edit")
//		                		{
//		                			theVue.fmMenu.pics[0] = {"picid":result[0].FileId,"ismain":1};
//		                		}
//		                		else
//		                		{
//		                			theVue.fmMenu.pics.push({"picid":result[0].FileId,"ismain":1});
//		                		}
//		                		mui.toast( "上传成功" + result[0].HttpPath );
		                		p_callback(result[0]);
		                }
		                		
		            } else {
		                mui.toast( "上传失败: " + status );
		            }
		            wa.close();
	        		}
	        	);
	        	//mui.toast("m_strImgLocalPath="+m_strImgLocalPath);
	    		task.addFile(m_strImgLocalPath, {key:m_strImgLocalPath} );
	    		task.addData("userid","root");
	    		task.start();
    		}
    		else
    		{
    			mui.toast('请选择要上传的图片');
    		}
	}
    
    
    
        //加载页面初始化需要加载的图片信息  
        function showImgDetail (imgId,imgkey,id,src) {    
//          var html = "";  
//          html +='<div  id="Img'+imgId+imgkey+'" class="image-item ">';   
//          html +='    <img id="picBig" data-preview-src="" data-preview-group="1" '+src+'/>';  
//          html +='    <span class="del" onclick="delImg(\''+imgId+'\',\''+imgkey+'\','+id+');">';         
//          html +='        <div class="fa fa-times-circle"></div>';      
//          html +='    </span>';   
//          html +='</div>';  
//          $("#"+imgkey+"S").append(html);  
			m_strImgLocalPath = src;
			document.getElementById(imgkey).setAttribute("src",src);
			document.getElementById("butCut").disabled = false;  
        }  
        //删除图片  
        function delImg(imgId,imgkey,id){  
            var bts = ["是", "否"];  
            plus.nativeUI.confirm("是否删除图片？", function(e) {  
                    var i = e.index;  
                    if (i == 0) {  
                        var itemname=id+"img-"+imgkey;  
                        var itemvalue=plus.storage.getItem(itemname);  
                        if(itemvalue!=null){  
                            var index=itemvalue.indexOf(imgId+",");  
                            if(index==-1){//没有找到  
                                delImgfromint(imgId,imgkey,id,index);  
                            }else{   
                                delImgFromLocal(itemname,itemvalue,imgId,imgkey,index); //修改，加了一个index参数  
                            }  
                              
                        }else{  
                            delImgfromint(imgId,imgkey,id);   
                        }  
                    }  
                },"查勘", bts);  
            /*var isdel = confirm("是否删除图片？");  
            if(isdel == false){  
                return;  
            }*/  
              
              
        }  
        function delImgFromLocal(itemname,itemvalue,imgId,imgkey,index){  
                    var wa = plus.nativeUI.showWaiting();  
                    var left=itemvalue.substr(0,index-1);  
                    var right=itemvalue.substring(index,itemvalue.length);  
                    var end=right.indexOf("}");  
                    right=right.substring(end+1,right.length);  
                    var newitem=left+right;  
                    plus.storage.setItem(itemname,newitem);   
                    //myAlert("删除成功");  
                    $("#Img"+imgId+imgkey).remove();  
                    wa.close();  
        }  
        //选取图片的来源，拍照和相册  
        function showActionSheet(conf){  
        		m_bCutPic = false;//初始化是否切图状态为未切图
          var divid = conf.id;  
              var actionbuttons=[{title:"拍照"},{title:"相册选取"}];  
              var actionstyle={title:"选择照片",cancel:"取消",buttons:actionbuttons};  
              plus.nativeUI.actionSheet(actionstyle, function(e){  
                    if(e.index==1){  
                        getImage(divid);  
                    }else if(e.index==2){  
                        galleryImg(divid);  
                    }  
              } );  
               }  
        //相册选取图片  
              function galleryImg(divid) {  
                 plus.gallery.pick( function(p){  
                     plus.io.resolveLocalFileSystemURL(p, function(entry) {  
                    compressImage(entry.toLocalURL(),entry.name,divid);  
                }, function(e) {  
                    plus.nativeUI.toast("读取拍照文件错误：" + e.message);  
                });  
                 }, function ( e ) {  
                 }, {  
                filename: "_doc/camera/",  
                filter:"image"  
                 } );  
              }  
        // 拍照  
        function getImage(divid) {  
            var cmr = plus.camera.getCamera();  
            cmr.captureImage(function(p) { 
            	//plus.nativeUI.toast("拍照ok" ); 
                plus.io.resolveLocalFileSystemURL(p, function(entry) {  
                		plus.nativeUI.toast("拍照ok" ); 
                    compressImage(entry.toLocalURL(),entry.name,divid);  
                }, function(e) {  
                    plus.nativeUI.toast("读取拍照文件错误：" + e.message);  
                });  
            }, function(e) {  
            }, {  
                filename: "_doc/camera/",  
                index: 1  
            });  
        }  
        //压缩图片  
        function compressImage(url,filename,divid){  
            var name="_doc/upload/"+divid+"-"+filename;//_doc/upload/F_ZDDZZ-1467602809090.jpg  
            plus.zip.compressImage({  
                    src:url,//src: (String 类型 )压缩转换原始图片的路径  
                    dst:name,//压缩转换目标图片的路径  
                    quality:60,//quality: (Number 类型 )压缩图片的质量.取值范围为1-100  
                    overwrite:true//overwrite: (Boolean 类型 )覆盖生成新文件  
                },  
                function(event) {   
                    //uploadf(event.target,divid);  
                    var path = name;//压缩转换目标图片的路径  
                    //event.target获取压缩转换后的图片url路  
                    //filename图片名称  
                    
                    saveimage(event.target,divid,filename,path);  
                },function(error) {  
                    plus.nativeUI.toast("压缩图片失败，请稍候再试");  
            });  
        }  
        //保存信息到本地  
        /**  
         *   
         * @param {Object} url  图片的地址  
         * @param {Object} divid  字段的名称  
         * @param {Object} name   图片的名称  
         */  
        function saveimage(url,divid,name,path){  
            var  state=0;  
            var wt = plus.nativeUI.showWaiting();  
          //  plus.storage.clear();   
            name=name.substring(0,name.indexOf("."));  
            var id = document.getElementById("ckjl.id").value;  
            var itemname=id+"img-"+divid;  
            var itemvalue=plus.storage.getItem(itemname);  
            if(itemvalue==null){  
                itemvalue="{"+name+","+path+","+url+"}";  
            }else{    
                itemvalue=itemvalue+"{"+name+","+path+","+url+"}";  
            }  
            plus.storage.setItem(itemname, itemvalue);  
              
            //var src = 'src="'+url+'"';  
            //alert(url);  
            showImgDetail(name,divid,id,url);  
            wt.close();  
              
        }  
        //上传图片，实例中没有添加上传按钮  
        function uploadimge(agree,back) {  
        //plus.storage.clear();  
         var wa = plus.nativeUI.showWaiting();  
         var DkeyNames=[];  
         var id = document.getElementById("ckjl.id").value;   
         var length=id.toString().length;   
         var idnmae=id.toString();  
         var numKeys=plus.storage.getLength();  
         var task = plus.uploader.createUpload('http://demo.dcloud.net.cn/helloh5/uploader/upload.php', {  
                                method: "POST"  
                            },  
                            function(t, status) {  
                                if (status == 200) {  
                                    console.log("上传成功");  
                                } else {  
                                    wa.close();  
                                    console.log("上传失败");   
                                }  
                            }  
                        );  
            task.addData("id",id);  
            for(var i=0; i<imgArray.length;i++){    
                var itemkey=id+"img-"+imgArray[i];  
                if(plus.storage.getItem(itemkey)!=null){  
                    var itemvalue=plus.storage.getItem(itemkey).split("{");  
                    for(var img=1;img<itemvalue.length;img++){  
                        var imgname=itemvalue[img].substr(0,itemvalue[img].indexOf(","));  
                        var imgurl=itemvalue[img].substring(itemvalue[img].indexOf(",")+1,itemvalue[img].lastIndexOf(","));  
                        task.addFile(imgurl,{key:imgurl});  
                    }  
                }  
            }  
            task.start();  
              
        }  
</script> 		
		
	</body>

</html>